package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.admin.utils.UploadUtil;
import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelCommend;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.query.TravelCommendQueryObject;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.utils.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Controller
@RequestMapping("/travelCommend")
public class TravelCommendController {

    @Autowired
    private ITravelCommendService commendService;

    @RequestMapping("list")
    public String list(@ModelAttribute("qo")TravelCommendQueryObject qo, Model model){
        qo.setOrderBy("tr.schedule desc");
        model.addAttribute("pageInfo",commendService.query(qo));

        return "/travelCommend/list";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(TravelCommend travelCommend, MultipartFile multipartFile) {
        JSONResult result = new JSONResult();
        try{
            if(travelCommend.getId()==null){
                //判断是否重复推荐
                Long travelId = travelCommend.getTravel().getId();
                if(commendService.selectByTravelId(travelId)!=null){
                    throw new RuntimeException("游记推荐添加重复,请更改");
                }
            }

            //判断是否传入新的图片
            if(multipartFile!=null&&multipartFile.getSize()>0){
                String imagePath = UploadUtil.upload(multipartFile, UploadUtil.IMG_BASE_PATH + "/upload");
                travelCommend.setCoverUrl(imagePath);
            }
            commendService.saveOrUpdate(travelCommend);

        }catch(Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }

        return result;
    }



}
